<?php
/**
 * TinyMVC - MysqlDriver.class.php file
 * 
 * @author Adrian Wieczorek <adi(at)tinymvc(dot)org>
 * @package TinyMVC
 * @subpackage Database
 * @version $Id: MysqlDriver.class.php 3 2007-09-11 12:08:07Z adi3ek $
 * 
 */

/**
 * This is a simple MySQL database driver, which should be used as a param in {@link Database::getInstance} first call
 * @package TinyMVC
 * @subpackage Database
 */
class MysqlDriver {
	/**
	 * connection handler
	 * @var resource
	 * @access private
	 */
	private $connection = null;
					
	/**
	 * @param string $dbHost mysql database hostname
	 * @param string $dbUser mysql database user
	 * @param string $dbPasswd mysql database user password
	 * @param string $dbName mysql database name
	 */
	public function __construct($dbHost, $dbUser, $dbPasswd, $dbName) {
		$this->connect($dbHost, $dbUser, $dbPasswd, $dbName);
	}
        
	private function connect($dbHost, $dbUser, $dbPasswd, $dbName) {   
		$this->connection = @mysql_connect($dbHost, $dbUser, $dbPasswd);
    
  if(!$this->connection) {
			throw new TinyMVCException("MysqlDriverException: connect($dbHost, $dbUser, *******) failed.");
  }            
    
		if(!@mysql_select_db($dbName, $this->connection)) {
   throw new TinyMVCException("MysqlDriverException: cannot use database: $dbName");
		}        
	}
								
	/**
	 * perform database query
	 * @param string $sql SQL query string
	 * @return MysqlResult 
	 */
	public function query($sql) {
  $result = null;
  $result = @mysql_query($sql, $this->connection);
  if(!$result) {
			$error = mysql_error($this->connection);
			throw new TinyMVCException('MysqlDriverException: invalid SQL: ' . $sql . ' <br /><b>Mysql Error:</b> ' . $error .'<br />');
  }
  return new MysqlResult($result, $this->connection);
	}
    			
}
